package com.itmuch.cloud.study.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mobile.device.Device;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.itmuch.cloud.study.entity.JwtUser;
import com.itmuch.cloud.study.service.JwtUserDetailsService;
import com.itmuch.cloud.study.util.JwtTokenUtil;
import com.itmuch.cloud.study.util.Message;

@RestController
public class LoginController {

    private String tokenHeader = "Authorization";


    private String secret="djfhsfweiocv454354nfd98fdsfnm3543d98vfdb";

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtUserDetailsService jwtUserDetailsService;
    
 
    //public static final String loginpwd = "$2a$10$qsYvMwvld7FMGKp45AQjpun6otC8b.eFN7Be5KAr0vuEQWgT.uvgm";
    public static  String loginpwd="";

    @PostMapping("/userLogin")
    public String userLogin(@RequestBody String user){
    	Message message = new Message();
    	message.setToken("");
    	JSONObject jo = new JSONObject(); 
    	if(user == null ||  user.equals("")){
    		message.setMsg("信息不能为空");
    		message.setSuccess("false");
    		jo.put("message", message);
    		return jo.toString();
    			
    	}
    	
    	JSONObject jsonObject = JSONObject.parseObject(user);
    	
    	if(jsonObject.get("userName") == null || jsonObject.get("userName").equals("")){
    		message.setMsg("用户名不能为空");
    		message.setSuccess("false");
    		jo.put("message", message);
    		return jo.toString();
    	}
    	if(jsonObject.get("passWord") == null || jsonObject.get("passWord").equals("")){
    		message.setMsg("密码不能为空");
    		message.setSuccess("false");
    		jo.put("message", message);
    		return jo.toString();
    	}
    	
		return login(jsonObject.getString("userName"), jsonObject.getString("passWord"));
    	
    }
    
    
    
    @RequestMapping(method=RequestMethod.POST , path = "/login", produces = "application/json;charset=utf8")
    public String login(@RequestParam(value="username") String username,@RequestParam(value="passwd") String passwd) {
    	PasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
    	loginpwd = passwordEncoder.encode(passwd);
    	UserDetails userDetails = userDetailsService.loadUserByUsername(username);
    	JSONObject jo = new JSONObject();
    	Message message = new Message();
    	message.setMsg("账号或密码错误");
    	message.setSuccess("false");
    	message.setToken("");
    	if(userDetails != null){
    		if(passwordEncoder.matches(passwd,userDetails.getPassword())){
    			List<JwtUser> users = jwtUserDetailsService.findByUserName(username, userDetails.getPassword());
    		
    			if (users == null || users.size() == 0) {
    				throw new BadCredentialsException("invalid key");
    			}
    			
    			final Authentication authentication = authenticationManager.authenticate(
    					new UsernamePasswordAuthenticationToken(
    							username,
    							passwd
    							)
    					);
    			SecurityContextHolder.getContext().setAuthentication(authentication);
    			
    			final String token = jwtTokenUtil.generateToken(users.get(0));
    			
    			//r = new HashMap<String,String>();
    		//	r.put("token", token);
    			
    			
    			message.setMsg("登录成功");
    			message.setSuccess("true");
    			message.setToken(token);
    			jo.put("message", message);
    		}else{
    			jo.put("message", message);
        		return jo.toJSONString();
        	}
    	}else{
    		jo.put("message", message);
    		return jo.toJSONString();
    	}
    	
        return jo.toJSONString();
    }
}
